package com.sanpu.kxe.business.main.presenter;

import android.content.DialogInterface;
import android.text.TextUtils;

import com.sanpu.kxe.base.BaseFragmentActivity;
import com.sanpu.kxe.business.main.bean.InviteMakeMoneyOutput;
import com.sanpu.kxe.business.main.bean.RebateTotalOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.bean.UserConfigOutput;
import com.sanpu.kxe.business.main.bean.WithdrawSignOutput;
import com.sanpu.kxe.business.main.contract.EarningsContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.business.trade.provider.ITradeProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;

import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：新收益presenter
 * Created by 薛勇军 on 2018/10/17.
 */

public class EarningsPresenter implements EarningsContract.Presenter {

    private EarningsContract.View mView;

    private CompositeSubscription mSubscription;

    private UserConfigOutput mConfigOutput;

    public EarningsPresenter(EarningsContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void getRebateTotal() {
        Subscription subscription = MainModel.getInstance().rebateTotal()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RebateTotalOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showRebateTotalView(null);
                    }

                    @Override
                    public void onNext(RebateTotalOutput output) {
                        if (output != null) {
                            CacheManage.getInstance().saveCache(CacheModel.REBATETOTAL, output);
                        }
                        mView.showRebateTotalView(output);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void withdrawSigning(final String withdrawMoney) {
        if (checkChkSts()) {
            mConfigOutput = CacheManage.getInstance().getCache(CacheModel.USER_CONFIG);
            if (mConfigOutput != null && (TextUtils.equals("SIGNED", mConfigOutput.getWithdrawSignStatus())
                    || TextUtils.equals("NONEED", mConfigOutput.getWithdrawSignStatus()))) {
                //已签约和不需要签约
                openWithdrawActivity(withdrawMoney);
            } else {
                ((BaseFragmentActivity) mView.getContext()).showLoadingDialog(false);
                Subscription subscription = MainModel.getInstance().withdrawSigning()
                        .subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<WithdrawSignOutput>() {
                            @Override
                            public void onCompleted() {
                                ((BaseFragmentActivity) mView.getContext()).dismissLoadingDialog();
                            }

                            @Override
                            public void onError(Throwable e) {
                                ((BaseFragmentActivity) mView.getContext()).dismissLoadingDialog();
                                ((BaseFragmentActivity) mView.getContext()).showErrorText(e);
                            }

                            @Override
                            public void onNext(WithdrawSignOutput withdrawSignOutput) {
                                if (withdrawSignOutput != null) {
                                    mConfigOutput.setWithdrawSignStatus(withdrawSignOutput.getSignStatus());
                                    CacheManage.getInstance().saveCache(CacheModel.USER_CONFIG, mConfigOutput);
                                    if (TextUtils.equals("SIGNED", withdrawSignOutput.getSignStatus())
                                            || TextUtils.equals("NONEED", withdrawSignOutput.getSignStatus())) {
                                        //已签约和不需要签约
                                        openWithdrawActivity(withdrawMoney);
                                    } else if (!TextUtils.isEmpty(withdrawSignOutput.getRedirectUrl())) {
                                        openWithdrawSigning(withdrawSignOutput.getRedirectUrl());
                                    }
                                }
                            }
                        });
                mSubscription.add(subscription);
            }
        }
    }

    @Override
    public void inviteMakeMoney() {
        Subscription subscription = MainModel.getInstance().inviteMakeMoney()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<InviteMakeMoneyOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<InviteMakeMoneyOutput> inviteFriendsOutputs) {
                        mView.showInviteMakeMoneyData(inviteFriendsOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 检验是否实名
     */
    private boolean checkChkSts() {
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null) {
            final String authenState = centerOutput.getChkSts();
            String remark = null;
            if (TextUtils.equals(CommonConfig.AUTHEN_NOTSUB, authenState)) {
                remark = "请先进行实名认证";
            } else if (TextUtils.equals(CommonConfig.AUTHEN_AUDIT, authenState)) {
                remark = "实名认证正在审核中，请稍候";
            } else if (TextUtils.equals(CommonConfig.AUTHEN_NOPASS, authenState)) {
                remark = "实名认证审核失败，请重新提交审核";
            }

            if (!TextUtils.isEmpty(remark)) {
                GlobalDialog dialog = new GlobalDialog(mView.getContext()).content(remark);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (!TextUtils.equals(CommonConfig.AUTHEN_AUDIT, authenState)) {
                            IMainProvider provider = PublicProviderUtil.getProvider(IMainProvider.class);
                            if (provider != null) {
                                provider.openCertificationActivity(mView.getContext(), false);
                            }
                        }
                    }
                });
                dialog.show();
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 去提现
     */
    private void openWithdrawActivity(String withdrawMoney) {
        ITradeProvider provider = PublicProviderUtil.getProvider(ITradeProvider.class);
        if (provider != null) {
            provider.openWithdrawActivity(mView.getContext(), withdrawMoney);
        }
    }

    /**
     * 去签约
     */
    private void openWithdrawSigning(final String redirectUrl) {
        DialogUtil.getInstance().dialogExistTitleTwoBtnHaveCallBack(mView.getContext(), "提示",
                "开通提现需要签约", "取消", "开始签约", new DialogViewListener() {
                    @Override
                    public void btnRightConfirm() {
                        MainOpenProvider.getInstance().openBrowserX5Activity(mView.getContext(), redirectUrl, true);
                    }

                    @Override
                    public void btnLeftCancel() {

                    }
                });
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
